package com.example.contentproviderapplication;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<File> mp3Files;//数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView lvData= (ListView) findViewById(R.id.lv_data);//控件
        //获取音频文件的数据
        //通过系统应用提供的Uri（数据的地址）
        //sd卡音乐媒体文件的Uri
        Uri sdUri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        //内存的媒体文件的Uri
        Uri memUri=MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
        //内容解析者
        ContentResolver resolver=getContentResolver();
        Cursor cursor=resolver.query(memUri,new String[]{"_data"},null,null,null);
        mp3Files=new ArrayList<>();
        while (cursor.moveToNext()){
            String path=cursor.getString(0);//结果集中只保留了一个_data字段
            File file=new File(path);
            mp3Files.add(file);
        }
        cursor.close();
        /*


        //通过内容解析者对象，解析这个Uri
        ContentResolver resolver=getContentResolver();
        Cursor cursor=resolver.query(sdUri,null,null,null,null);
        //从结果集中，找到_data字段的值（文件路径），封装成File，添加到列表
        mp3Files=new ArrayList<>();
        while (cursor.moveToNext()){
            String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            File file=new File(path);
            mp3Files.add(file);
        }
        */
        //加适配器
        lvData.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return mp3Files.size();
            }

            @Override
            public Object getItem(int i) {
                return null;
            }

            @Override
            public long getItemId(int i) {
                return 0;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                TextView tvItem=new TextView(getApplicationContext());
                tvItem.setText(mp3Files.get(i).getAbsolutePath());
                return tvItem;
            }
        });


    }
}
